package com.lxk.interceptor;

import com.lxk.dao.BlogDbDao;
import com.lxk.dao.CommentDao;
import com.lxk.domain.BlogDbEntity;
import com.lxk.domain.CommentDbEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by Lxk on 2020/6/23.
 */
public class RecentBlogInterceptor extends HandlerInterceptorAdapter {

    private BlogDbDao blogDbDao;

    private CommentDao commentDao;

    public RecentBlogInterceptor(BlogDbDao blogDbDao, CommentDao commentDao) {
        this.blogDbDao = blogDbDao;
        this.commentDao = commentDao;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (modelAndView != null) {
            List<BlogDbEntity> blogDbEntityList = blogDbDao.listRecentN(Integer.MAX_VALUE);
            modelAndView.addObject("newBlogs", blogDbEntityList.subList(0,3));
            //总访问量
            Integer pageView = blogDbEntityList.stream().mapToInt(each -> each.getViewCount()).sum();
            modelAndView.addObject("pageViewTotal", pageView);
            //总发布博客量
            modelAndView.addObject("blogTotal", CollectionUtils.isEmpty(blogDbEntityList) ? 0 : blogDbEntityList.size());
            //总评论量
            List<CommentDbEntity> comments = commentDao.queryAllComment();
            modelAndView.addObject("commentTotal", CollectionUtils.isEmpty(comments) ? 0 : comments.size());
        }
        super.postHandle(request, response, handler, modelAndView);
    }
}
